package com.carrot.gateway.util;

import com.carrot.common.core.domain.R;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

/**
 * 返回结果工具类
 *
 * @author 周鹏程
 * @date 2021/12/23 17:27
 */
@Slf4j
public final class ResultUtil {

	/**
	 * 返回
	 * @param response response
	 * @param objectMapper Json处理类
	 * @return Mono
	 */
	public static Mono<Void> result(
			ServerHttpResponse response, ObjectMapper objectMapper, R<?> resultWrapper) {
		// 设置返回格式
		response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
		return response.writeWith(Mono.fromSupplier(() -> {
			DataBufferFactory bufferFactory = response.bufferFactory();
			try {
				return bufferFactory.wrap(objectMapper.writeValueAsBytes(resultWrapper));
			}
			catch (JsonProcessingException e) {
				log.error("Error writing response", e);
				return bufferFactory.wrap(new byte[0]);
			}
		}));
	}

	private ResultUtil(){}
}
